<?php
declare (strict_types = 1);

namespace command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Env;

/**
 * 初始化优科框架，创建基本数据表，插入默认管理员
 */
class Init extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('ykinit')
             ->addOption('admin', null, Option::VALUE_REQUIRED, 'admin login name')
             ->addOption('pass', null, Option::VALUE_REQUIRED, 'admin login password')
             ->setDescription('init ykframework');
    }

    protected function execute(Input $input, Output $output)
    {
        
        $sql = file_get_contents(__DIR__ .  DIRECTORY_SEPARATOR . 'yokebase.sql');//获取框架sql文件

        $sql = preg_replace("/(\/\*(\s|.)*?\*\/)|(--(\s*)?(.*))|(\/\/.(\s|.*))|(#(\s*)?(.*))/", '', str_replace(array("\r\n", "\r"), "\n", $sql));

        $prefix = Env::get('database.prefix', '');

        if($prefix) $sql = str_replace('yk_',$prefix,$sql);        

        $sqlArr = explode(';',$sql);

        foreach ($sqlArr as $value) {
            $sqlstr = trim($value);
            if($sqlstr) Db::execute($sqlstr);
        }
        
        //添加内置角色
        $role_id = Db::name('role')->insertGetId(['role_name'=>'总管理员','role_desc'=>'系统内置最高权限角色','type'=>1]);

        //添加总管理员
        $admin_name = 'admin';
        if ($input->hasOption('admin')) {
            $admin_name = $input->getOption('admin');
        }
        $password = '123456';
        if ($input->hasOption('pass')) {
            $password = $input->getOption('pass');
        }
        $salt = mt_rand(1000,9999);
        $password = sha1($password.$salt);
        Db::name('admin')->save(['admin_name'=>'总管理员','login_name'=>$admin_name,'password'=>$password,'salt'=>$salt,'type'=>1,'role_id'=>$role_id]);
    	// 指令输出
    	$output->writeln('init success');
    }

    
}
